package com.snapp.web;

import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.oreilly.servlet.MultipartRequest;
import com.snapp.util.object.DBObject;

public class SNAppAccess {
	private static Logger logger = Logger.getLogger(SNAppAccess.class);
	
	public static DBObject getAccess(HttpServletRequest req) {
		DBObject access = null;
		if (isValid(req)) {
			return (DBObject)req.getSession().getAttribute("access");
		}
		return access;
	}
	/**
	 * Simple check for a session..
	 * @param req
	 * @return
	 */
	public static boolean isValid(HttpServletRequest req) {
		boolean rv = false;
		HttpSession sess = req.getSession();
		if (sess.getAttribute("access") != null) {
			rv = true;
		} 
		return rv;
	}
	
	/**
	 * This method requests the session permits.  If the requested function code (mnemonic) is not found or
	 * the hashCode does not match, this is not a safe request.
	 * 
	 * @param req
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static boolean isSecure(HttpServletRequest req) {
		boolean rv = false;
		String secCheck = req.getParameter("secCheck");
		
		if (secCheck != null) {
			// parse security check
			String[] psec = secCheck.split("::");
			
			// get permits from the session
			HashMap<String, String> permits = (HashMap<String, String>)req.getSession().getAttribute("permits");
			
			// check session and permits
			rv = (isValid(req) && permits.containsKey(psec[0]) && permits.get(psec[0]).equals(psec[1]));

			try {
				logger.info("Security Check:  "+psec[0]+": " + psec[1] + " = "+permits.get(psec[0]));
			} catch(Exception e) {}
		} else {
			logger.warn("Missing required \"secCheck\" parameter!");
		}
		
		return rv;
	}

	/**
	 * Use multipart request
	 * @param mpreq
	 * @param req
	 * @return
	 */
	public static boolean isSecure(MultipartRequest mpreq, HttpServletRequest req) {
		boolean rv = false;
		String secCheck = mpreq.getParameter("secCheck");
		
		if (secCheck != null) {
			// parse security check
			String[] psec = secCheck.split("::");
			
			// get permits from the session
			@SuppressWarnings("unchecked")
			HashMap<String, String> permits = (HashMap<String, String>)req.getSession().getAttribute("permits");
			
			// check session and permits
			rv = (isValid(req) && permits.containsKey(psec[0]) && permits.get(psec[0]).equals(psec[1]));

			try {
				logger.info("Security Check:  "+psec[0]+": " + psec[1] + " = "+permits.get(psec[0]));
			} catch(Exception e) {}
		} else {
			logger.warn("Missing required \"secCheck\" parameter!");
		}
		
		return rv;
	}

}
